package com.example.jpetstoreclient.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.jpetstoreclient.common.CommonResponse;
import com.example.jpetstoreclient.domain.Animal;
import com.example.jpetstoreclient.domain.Collection;
import com.example.jpetstoreclient.persistance.CollectionMapper;
import com.example.jpetstoreclient.service.AnimalService;
import com.example.jpetstoreclient.service.CollectionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service("collectionService")
public class CollectionServiceImpl extends ServiceImpl<CollectionMapper, Collection> implements CollectionService {

    @Autowired
    AnimalService animalService;

    @Override
    public CommonResponse<Collection> addCollection(int user_id,int animal_id){
        Collection collection = new Collection(user_id,animal_id);
        if(save(collection))return CommonResponse.createForSuccess("添加收藏成功！",collection);
        else return CommonResponse.createForError("添加收藏失败！");
    }

    @Override
    public CommonResponse<Object> deleteCollection(int collection_id){
        if(removeById(collection_id))return CommonResponse.createForSuccessMessage("取消收藏成功！");
        else return CommonResponse.createForError("取消失败！");
    }

    @Override
    public CommonResponse<List<Collection>> getAllCollections(int user_id){
        QueryWrapper<Collection> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id",user_id);
        List<Collection> collections = list(wrapper);
        for(Collection collection : collections){
            int animal_id = collection.getAnimal_id();
            Animal animal = animalService.getById(animal_id);
            collection.setAnimal(animal);
        }
        return CommonResponse.createForSuccess("查询所有收藏",collections);
    }

    @Override
    public CommonResponse<Boolean> isCollected(int user_id, int animal_id) {
        QueryWrapper<Collection> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id",user_id)
                .eq("animal_id",animal_id);
        Collection collection = getOne(wrapper);
        if(collection == null)return CommonResponse.createForSuccess("未收藏",false);
        else return CommonResponse.createForSuccess("已收藏",true);
    }
}
